package com.itheima.config;

import com.itheima.constants.SystemConstant;
import com.itheima.tool.MobileTool;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiEmbeddingModel;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringAIConfig {

    //向量数据库bean对象
    @Bean
    public VectorStore vectorStore(OpenAiEmbeddingModel openAiEmbeddingModel){
        return SimpleVectorStore.builder(openAiEmbeddingModel).build();
    }

    @Bean
    public ChatClient chatClient(OpenAiChatModel openAiChatModel, ChatMemory chatMemory,VectorStore vectorStore, MobileTool mobileTool) {
        return ChatClient.builder(openAiChatModel)
                .defaultSystem(SystemConstant.SYSTEM_ROLE)//系统角色和背景任务
                .defaultAdvisors(new SimpleLoggerAdvisor())//添加日志增强器（大模型调用前后都会记录日志）
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build()) //添加对话记忆增强器
                .defaultAdvisors(QuestionAnswerAdvisor.builder(vectorStore)
                        .searchRequest(SearchRequest.builder()
                                .topK(3)
                                .similarityThreshold(0.7)
                                .build())
                        .build())
                .defaultTools(mobileTool)//注册工具（FunctionCalling技术方案会用到）
                .build();//构建对话实例
    }
}
